import React, {useEffect, useState} from 'react'
import {connectComponent} from '../../../store/utils'
import {bindErrorActions, ErrorActionsType} from '../../../store/action/error'
import {CONSTANTS} from '../../../../constants'
import {apiPost} from '../../../api'
import {LSKeys, LSMethods} from '../../../storage'
import {AuthActionsType, bindAuthActions} from '../../../store/action/auth'
import {formatToUI} from '../../../utils/date'
import {Loading} from '../../../ui/loading/Loading'
import {Link} from 'react-router-dom'
import {IOrderHistory} from '../../../../api/IOrderHistory'
import {CartDto} from '../../../../api/CartDto'

export interface OrderHistoryContainerProps {
  cart: CartDto
  authActions: AuthActionsType
  errorActions: ErrorActionsType
}

const OrderHistoryContainer: React.FC<OrderHistoryContainerProps> = ({
  cart,
  authActions,
  errorActions,
}): React.ReactElement => {
  const [list, setList] = useState<IOrderHistory[]>(undefined)

  const loadHistory = async (): Promise<void> => {
    const token = LSMethods.getStorageData(LSKeys.TOKEN)
    const url = CONSTANTS.apiUrl + '/order/list'
    const res = await apiPost(url, {token: token}, {})
    const loadedList: IOrderHistory[] = res.result
    setList([...loadedList])
  }

  useEffect(() => {
    loadHistory()
  }, [])

  const renderList = (): React.ReactNode => {
    let items: React.ReactNode[] = []

    for (const item of list || []) {
      items.push(
        <Link key={item.id} to={'/order-history/' + item.id}>
          <div className={'order-history-list-item'}>
            <p className={'order-name'}>Заказ на {formatToUI(item.date)}</p>
            <p className={'order-price'}>{item.sum} &#8381;</p>
          </div>
        </Link>,
      )
    }

    if (items?.length > 0) {
      return <div className={'order-history-list'}>{items}</div>
    } else {
      return (
        <div className={'d-flex flex-column align-items-center'}>
          <p>Список пуст</p>
        </div>
      )
    }
  }

  if (!list) {
    return <Loading />
  }

  return (
    <div className={'order-history-wrapper'}>
      <h1 className={'order-history-header'}>История заказов</h1>
      {renderList()}
    </div>
  )
}

export default connectComponent(
  (state, props) => ({
    user: state.auth.user,
    cart: state.auth.cart,
  }),
  (dispatch) => ({
    authActions: bindAuthActions(dispatch),
    errorActions: bindErrorActions(dispatch),
  }),
  OrderHistoryContainer,
)
